<?php

/**
 * Description of UserController
 *
 * @author tuancasi
 */
class UserController extends Controller {

    public function filters() {
	parent::filters();
	return array(
	    'accessControl'
	);
    }

    public function accessRules() {
	return array(
	    array('allow', // allow all users to perform 'index' and 'view' actions
		'actions' => array('view', 'friend'),
		'users' => array('*'),
	    ),
	    array('allow',
		'actions' => array(
		    'index', 'update', 'list_member', 'get_list_email'
		),
		'users' => array('@')
	    ),
	    array('deny', // deny everybody else
		'users' => array('*')
	    )
	);
    }

    public function actionIndex() {
	
    }

    public function actionUpdate() {
	$error = '';
	$modelUser = User::model()->findByPk(user()->getModel()->user_id);

	if (isset($_POST['save'])) {
	    $modelUser->attributes = $_POST['User'];
	    $modelUser->repassword = $_POST['User']['repassword'];
	    $modelUser->display_name = $_POST['User']['first_name'] . ' ' . $_POST['User']['last_name'];
	    $modelUser->birthdate = $_POST['User']['year'] . '-' . $_POST['User']['month'] . '-' . $_POST['User']['day'];
	    //check old pass
	    if ($_POST['oldPassword']) {
		if ($modelUser->validatePassword($_POST['oldPassword'])) {
		    $modelUser->scenario = "edit";
		} else {
		    $error = 'Your old password is not match.';
		}
	    }

	    //check if there is a error
	    if (!$error) {
		if ($modelUser->validate()) {

		    if (isset($_FILES['avatar']['name'])) {
			//if user have avatar

			$statusUpload = uploadImg(AVATAR_PATH, $_FILES['avatar']['tmp_name'], $_FILES['avatar']['name']);
			if (isset($statusUpload['success']) && $statusUpload['success']) {
			    if ($modelUser->avatar) {
				deleteFile(AVATAR_PATH . $modelUser->avatar);
			    }
			    $modelUser->avatar = $statusUpload['name'];
			} else {
			    if (isset($statusUpload['error']) && $statusUpload['error']) {
				$error = $statusUpload['message'];
			    }
			}
			$modelUser->save();
			$modelUser = User::model()->findByPk(user()->getModel()->user_id);
			user()->setModel($modelUser);
		    }
		}
	    }
	}
	$modelUser->password = '';
	$modelUser->repassword = '';
	$this->render('update', array(
	    'modelUser' => $modelUser,
	    'error' => $error
	));
    }

    /*
     * 
     */

    public function actionView($id) {

	$modelUser = $this->_loadModel($id);
	$model = new Posts();

	/*
	 * get six friend of user 
	 */
	$modelFriend = Friend::model()->with('user')->findAll(array(
	    'condition' => 't.user_id=' . $id,
	    'order' => 'rand()',
	    'limit' => 3
	));

	//get post 
	$critical = new CDbCriteria();
	//connenct categories table based on relationship method
	$critical->with = array('user');

	//get all friend 
	$aIdsFriend = Friend::getIdsFriend($id);
	$sIdUser = $id;
//	if ($aIdsFriend) {
//	    foreach ($aIdsFriend as $item) {
//		$sIdUser .= ',' . $item;
//	    }
//	}
	$critical->addCondition('t.user_id IN(' . $sIdUser . ') ');

	$critical->order = 'post_id DESC';
	$iTotalRecord = $model->count($critical);

	$pages = new CPagination($iTotalRecord);
	$pages->pageSize = Posts::TOTAL_RECORD;
	$pages->applyLimit($critical);

	$this->render('view', array(
	    'modelUser' => $modelUser,
	    'aPosts' => $model->findAll($critical),
	    'pages' => $pages,
	    'iTotalRecord' => $iTotalRecord,
	    'modelFriend' => $modelFriend
	));
    }

    /**
     * list all friend of user
     */
    public function actionFriend($id) {

	$modelUser = $this->_loadModel($id);
	$model = new Friend('search');

	$model->unsetAttributes();  // clear any default values
	if (isset($_GET['Friend'])) {
	    $model->attributes = $_GET['Friend'];
	}
	$this->render('friend', array(
	    'model' => $model,
	    'modelUser' => $modelUser
	));
    }

    private function _loadModel($id) {
	$model = User::model()->findByPk($id);
	if ($model) {
	    return $model;
	} else {
	    throw new CHttpException(404, 'Page is not existed');
	}
    }

    /**
     * get list email for transfering to ajax
     */
    public function actionGet_list_email() {
	if (isset($_GET['term'])) {
	    $aFilterEmail = array();
	    $aEmail = User::getListEmail(user()->id, $_GET['term']);
	    if ($aEmail) {
		foreach ($aEmail as $email) {
		    $aFilterEmail[] = array(
			'value' => $email['email'],
			'label' => $email['email'],
			'id' => $email['user_id']);
		}
	    }
	    echo json_encode($aFilterEmail);
	    exit();
	}
    }

}

